<template>
  <div class="dashboard-bg">
    <!-- 顶部导航栏 -->
    <header class="dashboard-navbar">
      <div class="navbar-left">
        <img src="/src/assets/logo.png" class="logo" />
        <span class="school-title">日 照 市 卫 生 学 校</span>
      </div>
      <div class="navbar-right">
        <el-button type="danger" class="nav-btn" plain @click="handleLogout">退出</el-button>
      </div>
    </header>

    <!-- 主体内容 -->
    <main class="dashboard-main">
      <div class="info-section">
        <div class="grid-item notice-card left-card">
          <div class="notice-row">
            <el-icon class="notice-icon"><Document /></el-icon>
            <div class="notice-content">
              <div class="notice-desc" v-if="latestAnnouncement">
                {{ latestAnnouncement.content }}
              </div>
              <div class="notice-desc" v-else>
                欢迎使用智能工作台，您可在此查看最新公告、任务提醒等信息。
              </div>
            </div>
          </div>
          <!--  @click="router.push('/announcement/index')" -->
          <button class="notice-btn">系统公告</button>
        </div>
        <div class="grid-item profile-card left-card">
          <div class="profile-row">
            <span class="profile-avatar"><el-icon><User /></el-icon></span>
            <div class="profile-info">
              <div class="profile-name">姓名：{{ user?.name || '-' }}</div>
              <div class="profile-id">账号：{{ user?.username || '-' }}</div>
            </div>
          </div>
          <button class="profile-btn" @click="showProfileDialog = true">个人资料</button>
        </div>
      </div>
      <div class="modules-section">
        <div class="modules-grid">
          <div v-for="binding in userBindings" :key="binding.id" 
               class="grid-item module right-card" 
               :style="{ background: binding.bg_color || 'linear-gradient(135deg, #3a8dde 0%, #6ec6f3 100%)' }">
            <a :href="formatUrl(binding.url)" target="_blank" rel="noopener noreferrer" class="card-link">
              <div class="module-title">{{ binding.url_name }}</div>
            </a>
          </div>
        </div>
      </div>
    </main>

    <!-- 个人资料弹窗 -->
    <el-dialog
      v-model="showProfileDialog"
      title="个人资料"
      width="400px"
      :close-on-click-modal="false"
      class="profile-dialog"
    >
      <div class="profile-dialog-content">
        <div class="profile-info-item">
          <span class="label">姓名：</span>
          <span class="value">{{ user?.name || '-' }}</span>
        </div>
        <div class="profile-info-item">
          <span class="label">账号：</span>
          <span class="value">{{ user?.username || '-' }}</span>
        </div>
        <div class="password-form">
          <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef">
            <el-form-item label="旧密码" prop="oldPassword">
              <el-input v-model="passwordForm.oldPassword" type="password" show-password />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" show-password />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showProfileDialog = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="handleUpdatePassword" class="confirm-btn">确认修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Document, User } from '@element-plus/icons-vue'
import { getLatestAnnouncement } from '@/api/announcement'
import { getUserBindings } from '@/api/user'
import request from '@/utils/request'

const router = useRouter()
const user = ref(null)
const latestAnnouncement = ref(null)
const showProfileDialog = ref(false)
const passwordFormRef = ref(null)
const userBindings = ref([])

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const handleUpdatePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    
    const response = await request({
      url: '/api/users/update/password',
      method: 'post',
      data: {
        origin_password: passwordForm.value.oldPassword,
        new_password: passwordForm.value.newPassword,
        username: user.value.username
      }
    })
    
    if (response.code === 0) {
      ElMessage.success('密码修改成功')
      showProfileDialog.value = false
      passwordForm.value = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    } else {
      ElMessage.error(response.message || '密码修改失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '密码修改失败，请重试')
  }
}

// 获取用户绑定数据
const fetchUserBindings = async () => {
  try {
    const userStr = localStorage.getItem('user')
    if (!userStr) return
    
    const userData = JSON.parse(userStr)
    const response = await getUserBindings(userData.id)
    
    if (response.code === 0 && response.data) {
      userBindings.value = response.data
    }
  } catch (error) {
    console.error('Failed to fetch user bindings:', error)
    ElMessage.error('获取绑定数据失败')
  }
}

// 处理绑定项点击
const handleBindingClick = (binding) => {
  if (binding.url) {
    window.open(binding.url, '_blank')
  }
}

onMounted(async () => {
  const userStr = localStorage.getItem('user')
  if (userStr) {
    try {
      user.value = JSON.parse(userStr)
    } catch {
      user.value = null
    }
  }
  
  // 获取最新公告
  try {
    const res = await getLatestAnnouncement()
    if (res.code === 0 && res.data.items && res.data.items.length > 0) {
      latestAnnouncement.value = res.data.items[0]
    }
  } catch (error) {
    console.error('Failed to fetch latest announcement:', error)
  }

  // 获取用户绑定数据
  await fetchUserBindings()
})

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    router.push('/login')
  } catch {}
}

function formatUrl(url) {
  if (!/^https?:\/\//.test(url)) {
    return 'https://' + url.replace(/^\/+/, '');
  }
  return url;
}
</script>

<style lang="scss" scoped>

.dashboard-bg {
  min-height: 100vh;
  background: #10224a;
  display: flex;
  flex-direction: column;
}
.dashboard-navbar {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  height: 60px;
  background: #10224a;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 0 24px;
  .navbar-left {
    display: flex;
    align-items: center;
    .logo {
      width: 40px;
      height: 40px;
      margin-right: 14px;
    }
    .school-title {
      color: #fff;
      font-size: 22px;
      font-weight: bold;
      letter-spacing: 1px;
    }
  }
  .navbar-right {
    display: flex;
    align-items: center;
    gap: 4px;
    margin-right: 0;
    .nav-btn {
      font-size: 15px;
      border-radius: 4px;
      padding: 6px 18px;
    }
  }
}
.dashboard-main {
  width: 100%;
  max-width: 1200px; /* 恢复原始最大宽度（作为缩放基准） */
  transform-origin: top center; /* 缩放中心点设为顶部居中 */
  transform: scale(calc(min(1, (100vw - 48px) / 1200))); /* 动态计算缩放比例：当视口宽度超过1200px时开始缩小，最大1:1显示 */
  margin: 32px auto 0 auto;
  display: grid;
  grid-template-columns: minmax(280px, 320px) 1fr;
  gap: 4px;
  min-height: 440px;
  box-sizing: border-box;
  padding: 0 16px;
  align-items: start;
}

@media (max-width: 1024px) {
  .dashboard-main {
    grid-template-columns: 1fr;
  }
  .info-section {
    flex-direction: row;
    height: auto;
    gap: 24px;
  }
  .notice-card, .profile-card {
    height: 240px;
    min-width: 280px;
  }
}
.info-section {
  display: flex;
  flex-direction: column;
  gap: 4px;
  width: 100%;
  height: 620px;
  min-height: 0;
  box-sizing: border-box;
}
.notice-card, .profile-card {
  width: 100%;
  height: 300px;
  min-width: 0;
  min-height: 0;
  max-width: 100%;
  box-sizing: border-box;
}
.modules-section {
  height: 100%;
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  @media (max-width: 900px) {
    width: 100%;
    margin-top: 0;
    height: auto;
  }
}
.modules-grid {
  width: 100%;
  // height: 100%;
  overflow: hidden;
  display: flex;
  flex-wrap: wrap;
  // justify-content: space-around;
  // gap: 4px;

}


.module {
  padding: 4vw 3vw 6vw 3vw;
  .module-title {
    font-size: 3.2vw;
    margin-top: 18px;
    line-height: 1.2;
  }
}

@media (max-width: 768px) {
  .module-title {
    font-size: 4vw;
  }
}

@media (max-width: 1024px) {
  .dashboard-main {
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 2.4vw;
    padding: 0 1.6vw;
  }
  .info-section, .modules-section {
    aspect-ratio: 1/1.2;
    min-width: 0;
  }
  .notice-card, .profile-card {
    height: auto;
    aspect-ratio: 1/1;
    padding: 2vw;
  }
  .modules-grid {
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 0.4vw;
  }
  .module {
    aspect-ratio: 1/1;
    padding: 4vw 3vw;
    .module-title {
      font-size: 2.2vw;
      margin-top: 1.8vw;
    }
  }
  .school-title {
    font-size: 2.2vw;
  }
  .notice-desc {
    font-size: 1.4vw;
  }
  .profile-name, .profile-id {
    font-size: 1.6vw;
  }
}
.grid-item,
.module {
  background: rgba(255, 255, 255, 0.92);
  border-radius: 0 !important;
  box-shadow: none !important;
  border: 1.5px solid rgba(58, 141, 222, 0.10);
  backdrop-filter: blur(4px);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 36px 24px 56px 24px;
  min-height: 140px;
  height: 100%;
  cursor: pointer;
  transition: none !important;
  position: relative;
  overflow: hidden;
  &:hover {
    box-shadow: none !important;
    border-color: inherit !important;
    transform: none !important;
    transition: none !important;
    cursor: default;
  }
}
.notice-card {
  background: linear-gradient(135deg, #3a8dde 0%, #6ec6f3 100%);
  border-radius: 0 !important;
  box-shadow: none !important;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px 20px 56px 20px;
  min-height: 100px;
  position: relative;
  width: 100%;
  height: 300px;
  min-width: 0;
  min-height: 0;
  max-width: 100%;
  box-sizing: border-box;
  .notice-row {
    display: flex;
    align-items: center;
    width: 100%;
  }
  .notice-icon {
    color: #fff;
    font-size: 36px;
    margin-right: 16px;
    margin-top: 0;
    flex-shrink: 0;
    display: flex;
    align-items: center;
  }
  .notice-content {
    flex: 1;
    display: flex;
    align-items: center;
    .notice-desc {
      color: #fff;
      font-size: 14px;
      opacity: 0.95;
    }
  }
  .notice-btn {
    position: absolute;
    left: 20px;
    bottom: 16px;
    margin-top: 0;
    background: #10224a;
    color: #fff;
    border: none;
    border-radius: 20px;
    font-size: 15px;
    font-weight: bold;
    padding: 7px 28px;
    cursor: pointer;
    align-self: flex-start;
    box-shadow: none;
    transition: none;
    text-align: center;
  }
}
@media (max-width: 900px) {
  .notice-card {
    height: calc(2 * ((100vw - 2 * 8px - 1 * 8px) / 2) + 8px);
  }
}
@media (max-width: 600px) {
  .notice-card {
    height: calc(2 * ((100vw - 2 * 8px) / 1));
  }
}
.profile-card {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  width: 100%;
  height: 300px;
  min-width: 0;
  min-height: 0;
  max-width: 100%;
  box-sizing: border-box;
  // margin-bottom: 27px;
}
.profile-row {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
}
.profile-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  text-align: left;
}
.profile-avatar {
  color: #222 !important;
  font-size: 36px;
  margin-right: 16px;
  margin-top: 0;
  flex-shrink: 0;
  display: flex;
  align-items: center;
}
.profile-name, .profile-id {
  color: #222 !important;
  font-size: 16px;
  font-weight: 500;
  line-height: 1.7;
}
.profile-btn {
  position: absolute;
  left: 20px;
  bottom: 16px;
  margin-top: 0;
  background: #10224a;
  color: #fff;
  border: none;
  border-radius: 20px;
  font-size: 15px;
  font-weight: bold;
  padding: 7px 28px;
  cursor: pointer;
  align-self: flex-start;
  box-shadow: 0 2px 8px rgba(16,34,74,0.08);
  transition: background 0.2s;
  text-align: center;
}
.module {
  border-radius: 0 !important;
  box-shadow: none !important;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  padding: 20px 20px 56px 20px;
  min-height: 100px;
  height: 100%;
  cursor: pointer;
  transition: none !important;
  .module-title {
    color: #fff;
    font-size: 32px;
    font-weight: bold;
    text-align: center;
    width: 100%;
    letter-spacing: 1.5px;
    margin-bottom: 10px;
    user-select: none;
    margin-top: 18px;
    line-height: 1.2;
  }
  .module-desc {
    color: #fff;
    font-size: 14px;
    opacity: 0.92;
  }
  &:hover {
    box-shadow: none !important;
    border-color: inherit !important;
    transform: none !important;
    transition: none !important;
    cursor: default;
  }
  &:active {
    box-shadow: none !important;
    transform: none !important;
  }
}
.dashboard-footer {
  width: 100%;
  text-align: center;
  color: rgba(255,255,255,0.8);
  font-size: 13px;
  line-height: 1.6;
  margin-top: 32px;
  margin-bottom: 12px;
}
.profile-dialog :deep(.el-dialog) {
  border-radius: 0 !important;
  box-shadow: none !important;
  background: #fff !important;
  padding: 0;
}
.profile-dialog :deep(.el-dialog__header) {
  background: #10224a;
  color: #fff;
  font-size: 20px;
  font-weight: bold;
  border-radius: 0 !important;
  padding: 18px 24px;
}
.profile-dialog :deep(.el-dialog__title) {
  color: #fff;
  font-size: 20px;
  font-weight: bold;
}
.profile-dialog :deep(.el-dialog__body) {
  padding: 32px 32px 16px 32px;
  background: #fff;
}
.profile-dialog-content {
  background: #fff;
  color: #222;
}
.profile-dialog-content .profile-info-item .label {
  color: #666;
  font-weight: 500;
}
.profile-dialog-content .profile-info-item .value {
  color: #222;
  font-weight: 500;
}
.profile-dialog .dialog-footer {
  background: #f5f7fa;
  border-top: 1px solid #ebeef5;
  padding: 16px 32px;
}
.profile-dialog .cancel-btn {
  border-color: #dcdfe6;
  color: #606266;
}
.profile-dialog .confirm-btn {
  background: #10224a;
  color: #fff;
  border: none;
}
.card-link {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  text-decoration: none;
  color: inherit;
}

@media (max-width: 900px) {
  .grid-item,
  .module {
    padding: 24px 10px 36px 10px;
    min-height: 100px;
    border-radius: 18px;
  }
  .module-title {
    font-size: 22px;
    margin-top: 10px;
  }
  .profile-card {
    height: calc(2 * ((100vw - 2 * 8px - 1 * 8px) / 2) + 8px);
  }
}

.grid-item:hover,
.module:hover,
.notice-card:hover,
.profile-card:hover {
  box-shadow: none !important;
  border-color: inherit !important;
  transform: none !important;
  transition: none !important;
  cursor: default;
}
.right-card {
  width: 278px;
  height: 148px;
  margin-left: 4px;
}
.right-card:nth-child(3n + 1) {
  margin-left: 0px!important; 
}
.right-card:nth-child(n + 4) {
  margin-top: 4px!important;
}

</style>